﻿
Namespace Validation

    Public NotInheritable Class DomainValidationRules

#Region " Declarations "

        Private _enumRequiredEntry As RequiredEntry = RequiredEntry.No

#End Region

#Region " Properties "

        Public Property RequiredEntry() As RequiredEntry
            Get
                Return _enumRequiredEntry
            End Get
            Set(ByVal Value As RequiredEntry)
                _enumRequiredEntry = Value
            End Set
        End Property

#End Region

#Region " Constructors "

        Private Sub New()
        End Sub

#End Region

#Region " Methods "

        Public Shared Function DomainRule(ByVal target As Object, ByVal e As RuleEventArgs) As Boolean

            Dim args As DomainRuleEventArgs = TryCast(e, DomainRuleEventArgs)

            If args Is Nothing Then
                Throw New ArgumentException(String.Format("Wrong type of event args passed to DomainRule.  Should have received DomainEventArgs but was passed {0}", e.GetType))
            End If

            Dim objPI As System.Reflection.PropertyInfo = target.GetType().GetProperty(args.PropertyName)
            Dim strPropertyValue As String = CType(objPI.GetValue(target, Nothing), String)

            If args.RequiredEntry = Validation.RequiredEntry.No AndAlso String.IsNullOrEmpty(strPropertyValue) Then
                Return True
            End If

            For Each s As String In args.Data

                If String.Compare(s, strPropertyValue, StringComparison.OrdinalIgnoreCase) = 0 Then
                    Return True
                End If

            Next

            Dim sb As New System.Text.StringBuilder(1024)
            sb.AppendFormat("The {0} did not match any of the following acceptable values", RuleEventArgs.GetPropertyFriendlyName(e))

            For Each s As String In args.Data
                sb.AppendFormat(", {0}", s)
            Next

            e.BrokenRuleDescription = sb.ToString
            Return False
        End Function

#End Region

    End Class

End Namespace
